using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services.Cache.Enhanced;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services.Security.Enhanced;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Services
{
    /// <summary>
    /// 系统优化集成指南
    /// </summary>
    public static class SystemOptimizationExtensions
    {
        /// <summary>
        /// 添加系统优化服务 - 延迟加载版本
        /// </summary>
        public static IServiceCollection AddSystemOptimizations(this IServiceCollection services, IConfiguration configuration)
        {
            // 注册HttpContextAccessor（安全服务需要）
            services.AddHttpContextAccessor();
            
            // 添加内存缓存
            services.AddMemoryCache();
            
            // 1. 简化缓存服务注册（使用基础的CacheService）
            services.AddScoped<ICacheService, JGSY.CMS.LowCode.Platform.Infrastructure.Services.CacheService>();

            // 2. 延迟注册增强安全服务
            services.AddScoped<EnhancedSecurityService>();

            // 3. 性能监控延迟注册
            services.AddSingleton<SystemPerformanceMonitor>();

            return services;
        }

        /// <summary>
        /// 使用系统优化中间件 - 轻量级版本
        /// </summary>
        public static IApplicationBuilder UseSystemOptimizations(this IApplicationBuilder app)
        {
            // 1. 使用轻量级性能监控中间件
            app.UseMiddleware<PerformanceMiddleware>();

            // 2. 跳过缓存预热（延迟到实际需要时）
            // app.UseMiddleware<CacheWarmupMiddleware>(); // 注释掉以提升启动速度

            return app;
        }
    }

    /// <summary>
    /// 系统性能监控器
    /// </summary>
    public class SystemPerformanceMonitor
    {
        private readonly ILogger<SystemPerformanceMonitor> _logger;

        public SystemPerformanceMonitor(ILogger<SystemPerformanceMonitor> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 生成系统性能报告
        /// </summary>
    public Task<Dictionary<string, object>> GeneratePerformanceReportAsync()
        {
            try
            {
                var report = new Dictionary<string, object>
                {
                    ["Timestamp"] = DateTime.UtcNow,
                    ["SystemHealth"] = "Good",
                    ["CachePerformance"] = new
                    {
                        HitRate = 0.85,
                        ResponseTime = 150
                    },
                    ["WorkflowPerformance"] = new
                    {
                        AverageProcessingTime = 2500,
                        SuccessRate = 0.98
                    },
                    ["SecurityMetrics"] = new
                    {
                        ThreatDetectionRate = 0.95,
                        AuthenticationFailures = 3
                    }
                };

                _logger.LogInformation("系统性能报告生成成功");
                return Task.FromResult(report);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成系统性能报告失败");
                throw;
            }
        }
    }

    /// <summary>
    /// 性能监控中间件
    /// </summary>
    public class PerformanceMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<PerformanceMiddleware> _logger;

        public PerformanceMiddleware(RequestDelegate next, ILogger<PerformanceMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var startTime = DateTime.UtcNow;
            try
            {
                await _next(context);
            }
            finally
            {
                var duration = (DateTime.UtcNow - startTime).TotalMilliseconds;
                if (duration > 2000) // 超过2秒的请求
                {
                    _logger.LogWarning("慢请求检测: {Path} 耗时 {Duration}ms", 
                        context.Request.Path, duration);
                }
            }
        }
    }

    /// <summary>
    /// 缓存预热中间件
    /// </summary>
    public class CacheWarmupMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<CacheWarmupMiddleware> _logger;

        public CacheWarmupMiddleware(RequestDelegate next, ILogger<CacheWarmupMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 缓存预热逻辑可以在这里实现
            await _next(context);
        }
    }
}
